<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 6/4/21
 * Time: 9:36 PM
 */

namespace app\api\controller\v1;

use LinCmsTp5\admin\exception\token\TokenException;
use think\facade\Cache;

class Base
{
    protected function setCodePub($data,$name)
    {
        $wxCodeUrl = sprintf(config('wx.code_url'),
            config('wx.app_id'),config('wx.app_secret'));
        $access_token = Cache::get('access_token');
        if(!$access_token)
        {
            $jsonInfo = curl_get($wxCodeUrl);
            $access_token = $jsonInfo["access_token"];
            $expire_in = config('setting.token_expire_in');
            $result = cache('access_token',$access_token,$expire_in);
            if(!$result)
            {
                throw new TokenException([
                    'msg' => '服务器缓存异常',
                    'errorCode' => 10005
                ]);
            }
        }
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$access_token;
        $res = https_post($url,json_encode($data));
        if(strstr($res, 'errcode')) {
            $jsonInfo = curl_get($wxCodeUrl);
            $access_token = $jsonInfo["access_token"];
            $expire_in = config('setting.token_expire_in');
            $result = cache('access_token', $access_token, $expire_in);
            if (!$result) {
                throw new TokenException([
                    'msg' => '服务器缓存异常',
                    'errorCode' => 10005
                ]);
            }
            $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $access_token;
            $res = https_post($url, json_encode($data));

        }
        $file = fopen(config('setting.xd_prefix') . $name . '.png', "w");//打开文件准备写入
        fwrite($file, $res);//写入,$res为图片二进制内容
        fclose($file);//关闭
    }
}